#include "game_view.h"
#include "ui_game_view.h"
#include <QString>
#include <QDebug>
#include <QSqlQuery>
#include <QSqlError>
#include <QString>

game_view::game_view(QWidget *parent) :
    QWidget(parent),
    ui(new Ui::game_view),
    sqloperator(new SqlOperator)  // 初始化 SqlOperator 对象
{
    ui->setupUi(this);
    choose = new choose_hero();
    update = new class rest();

    QString heroName=choose->getName();
    ui->hero_name->setText(heroName);

    connect(ui->return_2, SIGNAL(clicked()), this, SIGNAL(goTostartgame()));

    connect(ui->choose_1, &QPushButton::clicked, this, [=]
    {
        this->fight1();
        emit rest();
        updatestart();
    });

    connect(ui->choose_2, &QPushButton::clicked, this, [=]
    {
        this->fight2();
        emit rest();
        updatestart();
    });



    // 使用工具类连接数据库a
    if (!sqloperator->open("./pro.db", "connectionName")) {
        qDebug() << "数据库连接失败：" << sqloperator->lastError();
        return;
    }

    // 调用函数更新UI

   // updateHeroValueLabel(heroName);

    gearCount = getGearCount();

    if (gearCount <= 0) {
        qDebug() << "未找到装备数据";
        return;
    }

    updatestart();
    // closeData();

}

game_view::~game_view()
{
    delete ui;
    delete sqloperator;
}

void game_view::updatestart()
{
    QString name1;
    int value1;
    int monsterCount = getMonsterCount();
    QList<QVariantList> data1 = getMonsterData(monsterCount);
        name1 = data1.first().at(0).toString();
        value1 = data1.first().at(1).toInt();
        updateMonsterUI1(name1, value1);

    // 初始化怪物2数据
    QString name2;
    int value2;
    QList<QVariantList> data2 = getMonsterData(monsterCount);
        name2 = data2.first().at(0).toString();
        value2 = data2.first().at(1).toInt();
        updateMonsterUI2(name2, value2);
}

// 获取怪物总数
int game_view::getMonsterCount()
{
    QList<QVariantList> data;
    // 使用工具类执行查询
    if (!sqloperator->selectDataBySql("select count(*) from monster", {"count(*)"}, data) || data.isEmpty()) {
        qDebug() << "查询怪物数量失败：" << sqloperator->lastError();
        return -1;
    }
    return data.first().first().toInt();
}

// 获取装备总数
int game_view::getGearCount()
{
    QList<QVariantList> data;
    // 使用工具类执行查询
    if (!sqloperator->selectDataBySql("select count(*) from gear", {"count(*)"}, data) || data.isEmpty()) {
        qDebug() << "查询装备数量失败：" << sqloperator->lastError();
        return 0;
    }
    //qDebug() << data;
    return data.first().first().toInt();
}

// 获取指定索引的随机怪物数据
QList<QVariantList> game_view::getMonsterData(int totalCount)
{
    if (totalCount <= 0) {

    }

    // 获取随机怪物ID并查询数据
    int randomId = sqloperator->getrandomoster(totalCount);
    QString sql = QString("select monster_name, monster_value from monster where monster_id = %1").arg(randomId);

    QList<QVariantList> data;
    if (!sqloperator->selectDataBySql(sql, {"monster_name", "monster_value"}, data) || data.isEmpty()) {
        qDebug() << "查询怪物数据失败：" << sqloperator->lastError();

    }

    // 提取查询结果
//    name = data.first().at(0).toString();
//    value = data.first().at(1).toInt();
    return data;
}

// 根据索引更新怪物UI
void game_view::updateMonsterUI1(const QString &name, int value)
{
    ui->moster_name_1->clear();
    ui->moster_name_1->setText(name);
    ui->HP_monster_1->clear();
    ui->HP_monster_1->setText(QString("%1%2").arg(ui->HP_monster_1->text()).arg(value));

}

void game_view::updateMonsterUI2(const QString &name, int value)
{
    ui->moster_name_2->clear();
    ui->moster_name_2->setText(name);
    ui->HP_monster_2->clear();
    ui->HP_monster_2->setText(QString("%1%2").arg(ui->HP_monster_2->text()).arg(value));
}

void game_view::on_return_2_clicked()
{

}

// 根据英雄名字查询并更新UI的函数
void game_view::updateHeroValueLabel(const QString& heroName)
{
    // 查询hero表中对应英雄的value和slot值
    QHash<QString, QVariant> whereConditions;
    whereConditions.insert("hero_name", heroName);
    QList<QString> fields = {"hero_value", "slot_head", "slot_chest", "slot_leg", "slot_foot", "slot_weapon"};
    QList<QVariantList> heroData;
    if (!sqloperator->selectData("hero", fields, whereConditions, heroData) || heroData.isEmpty()) {
        qDebug() << "查询英雄数据失败：" << sqloperator->lastError();
        return;
    }

    int totalValue = heroData.first().at(0).toInt();
    QList<int> slotIds;
    for (int i = 1; i < heroData.first().size(); ++i) {
        int slotId = heroData.first().at(i).toInt();
        if (slotId > 0) {
            slotIds.append(slotId);
        }
    }
    // 根据slot值查询gear表中的value值并累加
    for (int slotId : slotIds) {
        QHash<QString, QVariant> gearConditions;
        gearConditions.insert("gear_id", slotId);
        QList<QVariantList> gearData;
        if (sqloperator->selectData("gear", {"gear_value"}, gearConditions, gearData) &&!gearData.isEmpty()) {
            totalValue += gearData.first().at(0).toInt();
        }
    }
    // 新增：将总价值存入成员变量
    m_heroTotalValue = totalValue;

    // 更新UI（原有逻辑不变）
    ui->HP_user_1->setText(QString("%1").arg(totalValue));

}

void game_view::fight1()
{
    // 1. 获取怪物1的数值（从UI标签中提取）
    QString monster1HpText = ui->HP_monster_1->text();  // 格式如"HP: 10"
    int monster1Value = monster1HpText.remove("HP: ").toInt();  // 提取数值部分

    // 2. 比较英雄总价值与怪物数值
    gearName = getgear(gearCount);

    if (m_heroTotalValue > monster1Value) {
        QString name = "你掉落了:"+gearName;
        QMessageBox::information(this,"战斗结果：",name);
        addPack(gearName);
    } else {
        QMessageBox::information(this, "战斗结果", "你输了！");
    }
    this->close();
}

void game_view::fight2()
{
    // 1. 获取怪物1的数值（从UI标签中提取）
    QString monster1HpText = ui->HP_monster_2->text();  // 格式如"HP: 10"
    int monster2Value = monster1HpText.remove("HP: ").toInt();  // 提取数值部分

    // 2. 比较英雄总价值与怪物数值
    gearName = getgear(gearCount);
    if (m_heroTotalValue > monster2Value) {
        QString name = "你掉落了:"+gearName;
        QMessageBox::information(this,"战斗结果：",name);
        addPack(gearName);
    } else {
        QMessageBox::information(this, "战斗结果", "你输了！");
    }
}

QString game_view::getgear(int &gearCount)
{

    int randomId = sqloperator->getrandomgear(gearCount);
    QList<QVariantList> data;
    // 构造查询语句并使用工具类查询
    QString sql = QString("select gear_name from gear where gear_id = %1").arg(randomId);

    if (!sqloperator->selectDataBySql(sql, {"gear_name"}, data) || data.isEmpty()) {
        qDebug() << "查询怪物数据失败：" << sqloperator->lastError();
        return "1";
    }
    heroName = data.first().at(0).toString();
    return heroName;
}

void game_view::addPack(QString heroname)
{
    // 1. 准备SQL语句
    QString sql = QString("SELECT gear_name,gear_value,gear_slot_id FROM gear WHERE gear_name = '%1'").arg(heroname);

    // 2. 准备要查询的字段列表（与SQL中选择的字段对应）
    QList<QString> fields;
    fields << "gear_name" << "gear_value" << "gear_slot_id";

    // 3. 准备接收结果的变量
    QList<QVariantList> resultData;
    sqloperator->selectDataBySql(sql,fields,resultData);
    if(!sqloperator->insertRowsData("pack",fields,resultData))
    {
        QMessageBox::warning(this,"错误：","原因为："+sqloperator->lastError());
    }
}

void game_view::closeData()
{
    sqloperator->close();
}


void game_view::upDateUI()
{
    QString name1;
    int value1;
    int monsterCount = getMonsterCount();
    QList<QVariantList> data1 = getMonsterData(monsterCount);
        name1 = data1.first().at(0).toString();
        value1 = data1.first().at(1).toInt();
        updateMonsterUI1(name1, value1);

    // 初始化怪物2数据
    QString name2;
    int value2;
    QList<QVariantList> data2 = getMonsterData(monsterCount);
        name2 = data2.first().at(0).toString();
        value2 = data2.first().at(1).toInt();
        updateMonsterUI2(name2, value2);
}
